<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>基本资料</span>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <el-form
        v-else
        ref="profileForm"
        :model="userInfo"
        :rules="rules"
        label-width="100px"
        class="profile-form">

        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>

        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userInfo.nickname"></el-input>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="userInfo.sex">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userInfo.phone"></el-input>
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>

        <!-- 身份证号 -->
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="userInfo.idCard"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUserProfile, updateUserProfile } from '@/api/system/user'

export default {
  name: 'Profile',
  data() {
    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      if (value && !/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'))
      } else {
        callback()
      }
    }
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }
    // 身份证号验证规则
    const validateIdCard = (rule, value, callback) => {
      const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (value && !idCardReg.test(value)) {
        callback(new Error('请输入正确的身份证号码'));
      } else {
        callback();
      }
    };

    return {
      loading: false,
      userInfo: {
        id: undefined,
        username: '',
        nickname: '',
        sex: 0,
        phone: '',
        email: '',
        idCard: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        idCard: [
          { validator: validateIdCard, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUser()
  },
  methods: {
    // 获取用户信息
    getUser() {
      this.loading = true
      // 先尝试从Vuex store获取当前用户信息
      const storeUserInfo = this.$store.getters.user
      
      getUserProfile().then(response => {
        this.loading = false
        if (response.code === 200 && response.data) {
          // 根据后端返回的字段名映射
          this.userInfo = {
            id: response.data.userId || response.data.id,
            username: response.data.userName || response.data.username,
            nickname: response.data.nickName || response.data.nickname || '',
            sex: typeof response.data.sex === 'number' ? response.data.sex : 0,
            phone: response.data.phonenumber || response.data.phone || '',
            email: response.data.email || '',
            idCard: response.data.idCard || ''
          }
          
          // 如果后端没有返回数据，使用store中的用户信息
          if (!this.userInfo.username && storeUserInfo) {
            this.userInfo.username = storeUserInfo.name || ''
            this.userInfo.nickname = storeUserInfo.nickName || ''
          }
          
          console.log('获取到的用户信息:', this.userInfo)
        } else {
          this.$message.error('获取用户信息失败')
          // 降级处理：如果API调用失败，使用store中的用户信息
          if (storeUserInfo) {
            this.userInfo.username = storeUserInfo.name || ''
            this.userInfo.nickname = storeUserInfo.nickName || ''
          }
        }
      }).catch(error => {
        this.loading = false
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
        
        // 降级处理：如果API调用失败，使用store中的用户信息
        if (storeUserInfo) {
          this.userInfo.username = storeUserInfo.name || ''
          this.userInfo.nickname = storeUserInfo.nickName || ''
        }
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.profileForm.validate(valid => {
        if (valid) {
          this.loading = true
          updateUserProfile(this.userInfo).then(response => {
            this.loading = false
            if (response.code === 200) {
              this.$message.success('修改成功')
              // 更新store中的用户信息
              this.$store.dispatch('user/getInfo')
            } else {
              this.$message.error(response.msg || '修改失败')
            }
          }).catch(error => {
            this.loading = false
            console.error('修改用户资料失败:', error)
            this.$message.error('修改用户资料失败')
          })
        }
      })
    },
    // 重置表单
    resetForm() {
      this.getUser()
    }
  }
}
</script>

<style scoped>
.profile-form {
  max-width: 600px;
  margin: 0 auto;
}

.loading-container {
  padding: 30px;
  text-align: center;
}
</style>
